package com.woniuxy.qiantai.controller;


import com.woniuxy.qiantai.entity.Address;
import com.woniuxy.qiantai.entity.User;
import com.woniuxy.qiantai.service.AddressService;
import com.woniuxy.qiantai.service.UserService;
import com.woniuxy.qiantai.utils.CookieUtils;
import com.woniuxy.qiantai.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author woniumrwang
 * @since 2023-01-06 02:44:35
 */
@RestController
@RequestMapping("/address")
public class AddressController {

    @Autowired
    AddressService addressService;

    @Autowired
    UserService userService;

    @GetMapping("all")
    @ResponseBody
    public List<Address> all(HttpServletRequest request){

        User currentUser = getCurrentUser(request);

        List<Address> addressList = addressService.getAll(currentUser.getId());

        return addressList;
    }



    private User getCurrentUser(HttpServletRequest request){
        String userTokenFromCookie = CookieUtils.getUserTokenFromCookie(request);
        String currentUserAccount = JwtUtils.getAccountWithoutException(userTokenFromCookie);
        User currentUser = userService.getUserByAccount(currentUserAccount);

        return currentUser;
    }


    @RequestMapping("add")
    @ResponseBody
    public void add(Address address,HttpServletRequest request){

        User currentUser = getCurrentUser(request);

        addressService.addAddress(currentUser.getId(),address);

    }


}

